<!doctype html>
<!--
Copyright 2016 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">

    <!-- Origin Trial Token, feature = WebVR (For Chrome M59+), origin = https://webvr.info, expires = 2017-10-13 -->
    <meta http-equiv="origin-trial" data-feature="WebVR (For Chrome M59+)" data-expires="2017-10-13" content="Aqw0TUvp8CwZmgIS50pM1blhzy05y7OkBeW3AQQGjer4KuKV0p13xfrRbe2bT8B1+DgRW0O3Dda0yOjcL46GBwgAAABMeyJvcmlnaW4iOiJodHRwczovL3dlYnZyLmluZm86NDQzIiwiZmVhdHVyZSI6IldlYlZSMS4xIiwiZXhwaXJ5IjoxNTA3ODU5MDE4fQ==">

    <title>04 - Simple Mirroring</title>

    <!--
      This sample demonstrates how to mirror content to an external display
      while presenting to a VRDisplay.
    -->

    <style>
      #webgl-canvas {
        box-sizing: border-box;
        height: 100%;
        left: 0;
        margin: 0;
        position: absolute;
        top: 0;
        width: 100%;
      }
    </style>

    <!-- This entire block in only to facilitate dynamically enabling and
    disabling the WebVR polyfill, and is not necessary for most WebVR apps.
    If you want to use the polyfill in your app, just include the js file and
    everything will work the way you want it to by default. -->
    <script>
      var WebVRConfig = {
        // Prevents the polyfill from initializing automatically.
        DEFER_INITIALIZATION: true,
        // Ensures the polyfill is always active when initialized, even if the
        // native API is available. This is probably NOT what most pages want.
        ALWAYS_APPEND_POLYFILL_DISPLAY: true,
        // Polyfill optimizations
        DIRTY_SUBMIT_FRAME_BINDINGS: true,
        BUFFER_SCALE: 0.75,
      };
    </script>
    <script src="js/third-party/webvr-polyfill.js"></script>
    <script src="js/third-party/wglu/wglu-url.js"></script>
    <script>
      // Dynamically turn the polyfill on if requested by the query args.
      if (WGLUUrl.getBool('polyfill', false)) {
        InitializeWebVRPolyfill();
      } else {
        // Shim for migration from older version of WebVR. Shouldn't be necessary for very long.
        InitializeSpecShim();
      }
    </script>
    <!-- End sample polyfill enabling logic -->

    <script src="js/third-party/gl-matrix-min.js"></script>

    <script src="js/third-party/wglu/wglu-program.js"></script>
    <script src="js/third-party/wglu/wglu-stats.js"></script>
    <script src="js/third-party/wglu/wglu-texture.js"></script>

    <script src="js/vr-cube-sea.js"></script>
    <script src="js/vr-samples-util.js"></script>
  </head>
  <body>
    <canvas id="webgl-canvas"></canvas>
    <script>
      /* global mat4, VRCubeSea, WGLUStats, WGLUTextureLoader, VRSamplesUtil */
      (function () {
      "use strict";

      var vrDisplay = null;
      var frameData = null;
      var projectionMat = mat4.create();
      var viewMat = mat4.create();
      var vrPresentButton = null;

      // ================================
      // WebVR-specific code begins here.
      // ================================

      // WebGL setup.
      var gl = null;
      var cubeSea = null;
      var stats = null;

      function onContextLost( event ) {
        event.preventDefault();
        console.log( 'WebGL Context Lost.' );
        gl = null;
        cubeSea = null;
        stats = null;
      }

      function onContextRestored( event ) {
        console.log( 'WebGL Context Restored.' );
        initWebGL(vrDisplay ? vrDisplay.capabilities.hasExternalDisplay : false);
      }

      var webglCanvas = document.getElementById("webgl-canvas");
      webglCanvas.addEventListener( 'webglcontextlost', onContextLost, false );
      webglCanvas.addEventListener( 'webglcontextrestored', onContextRestored, false );

      function initWebGL (preserveDrawingBuffer) {
        // Setting preserveDrawingBuffer to true prevents the canvas from being
        // implicitly cleared when calling submitFrame or compositing the canvas
        // on the document. For the simplest form of mirroring we want to create
        // the canvas with that option enabled. Note that this may incur a
        // performance penalty, as it may imply that additional copies of the
        // canvas backbuffer need to be made. As a result, we ONLY want to set
        // that if we know the VRDisplay has an external display, which is why
        // we defer WebGL initialization until after we've gotten results back
        // from navigator.getVRDisplays and know which device we'll be
        // presenting with.
        var glAttribs = {
          alpha: false,
          preserveDrawingBuffer: preserveDrawingBuffer
        };
        var useWebgl2 = WGLUUrl.getBool('webgl2', false);
        var contextTypes = useWebgl2 ? ["webgl2"] : ["webgl", "experimental-webgl"];
        for (var i in contextTypes) {
          gl = webglCanvas.getContext(contextTypes[i], glAttribs);
          if (gl)
            break;
        }
        if (!gl) {
          var webglType = (useWebgl2 ? "WebGL 2" : "WebGL")
          VRSamplesUtil.addError("Your browser does not support " + webglType + ".");
          return;
        }
        gl.clearColor(0.1, 0.2, 0.3, 1.0);
        gl.enable(gl.DEPTH_TEST);
        gl.enable(gl.CULL_FACE);

        var textureLoader = new WGLUTextureLoader(gl);
        var texture = textureLoader.loadTexture("media/textures/cube-sea.png");
        cubeSea = new VRCubeSea(gl, texture);
        var enablePerformanceMonitoring = WGLUUrl.getBool(
            'enablePerformanceMonitoring', false);
        stats = new WGLUStats(gl, enablePerformanceMonitoring);

        // Wait until we have a WebGL context to resize and start rendering.
        window.addEventListener("resize", onResize, false);
        onResize();
        window.requestAnimationFrame(onAnimationFrame);
      }

      function onVRRequestPresent () {
        vrDisplay.requestPresent([{ source: webglCanvas }]).then(function () {
        }, function (err) {
          var errMsg = "requestPresent failed.";
          if (err && err.message) {
            errMsg += "<br/>" + err.message
          }
          VRSamplesUtil.addError(errMsg, 2000);
        });
      }

      function onVRExitPresent () {
        if (!vrDisplay.isPresenting)
          return;

        vrDisplay.exitPresent().then(function () {
        }, function () {
          VRSamplesUtil.addError("exitPresent failed.", 2000);
        });
      }

      function onVRPresentChange () {
        onResize();

        if (vrDisplay.isPresenting) {
          if (vrDisplay.capabilities.hasExternalDisplay) {
            VRSamplesUtil.removeButton(vrPresentButton);
            vrPresentButton = VRSamplesUtil.addButton("Exit VR", "E", "media/icons/cardboard64.png", onVRExitPresent);
          }
        } else {
          if (vrDisplay.capabilities.hasExternalDisplay) {
            VRSamplesUtil.removeButton(vrPresentButton);
            vrPresentButton = VRSamplesUtil.addButton("Enter VR", "E", "media/icons/cardboard64.png", onVRRequestPresent);
          }
        }
      }

      if (navigator.getVRDisplays) {
        frameData = new VRFrameData();

        navigator.getVRDisplays().then(function (displays) {
          if (displays.length > 0) {
            vrDisplay = displays[displays.length - 1];
            vrDisplay.depthNear = 0.1;
            vrDisplay.depthFar = 1024.0;

            if (vrDisplay.capabilities.canPresent)
              vrPresentButton = VRSamplesUtil.addButton("Enter VR", "E", "media/icons/cardboard64.png", onVRRequestPresent);

            // For the benefit of automated testing. Safe to ignore.
            if (vrDisplay.capabilities.canPresent && WGLUUrl.getBool('canvasClickPresents', false))
              webglCanvas.addEventListener("click", onVRRequestPresent, false);

            window.addEventListener('vrdisplaypresentchange', onVRPresentChange, false);
            window.addEventListener('vrdisplayactivate', onVRRequestPresent, false);
            window.addEventListener('vrdisplaydeactivate', onVRExitPresent, false);

            // Only use preserveDrawingBuffer if we have an external display to
            // mirror to.
            initWebGL(vrDisplay.capabilities.hasExternalDisplay);
          } else {
            initWebGL(false);
            VRSamplesUtil.addInfo("WebVR supported, but no VRDisplays found.", 3000);
          }
        }, function () {
          VRSamplesUtil.addError("Your browser does not support WebVR. See <a href='http://webvr.info'>webvr.info</a> for assistance.");
        });
      } else if (navigator.getVRDevices) {
        initWebGL(false);
        VRSamplesUtil.addError("Your browser supports WebVR but not the latest version. See <a href='http://webvr.info'>webvr.info</a> for more info.");
      } else {
        // No VR means no mirroring, so create WebGL content without
        // preserveDrawingBuffer
        initWebGL(false);
        VRSamplesUtil.addError("Your browser does not support WebVR. See <a href='http://webvr.info'>webvr.info</a> for assistance.");
      }

      function onResize () {
        if (vrDisplay && vrDisplay.isPresenting) {
          // If we're presenting we want to use the drawing buffer size
          // recommended by the VRDevice, since that will ensure the best
          // results post-distortion.
          var leftEye = vrDisplay.getEyeParameters("left");
          var rightEye = vrDisplay.getEyeParameters("right");

          // For simplicity we're going to render both eyes at the same size,
          // even if one eye needs less resolution. You can render each eye at
          // the exact size it needs, but you'll need to adjust the viewports to
          // account for that.
          webglCanvas.width = Math.max(leftEye.renderWidth, rightEye.renderWidth) * 2;
          webglCanvas.height = Math.max(leftEye.renderHeight, rightEye.renderHeight);
        } else {
          // We only want to change the size of the canvas drawing buffer to
          // match the window dimensions when we're not presenting.
          webglCanvas.width = webglCanvas.offsetWidth * window.devicePixelRatio;
          webglCanvas.height = webglCanvas.offsetHeight * window.devicePixelRatio;
        }
      }

      function onAnimationFrame (t) {
        // do not attempt to render if there is no available WebGL context
        if (!gl || !stats || !cubeSea) {
          return;
        }

        stats.begin();

        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

        if (vrDisplay) {
          vrDisplay.requestAnimationFrame(onAnimationFrame);

          vrDisplay.getFrameData(frameData);

          if (vrDisplay.isPresenting) {
            gl.viewport(0, 0, webglCanvas.width * 0.5, webglCanvas.height);
            cubeSea.render(frameData.leftProjectionMatrix, frameData.leftViewMatrix, stats, t);

            gl.viewport(webglCanvas.width * 0.5, 0, webglCanvas.width * 0.5, webglCanvas.height);
            cubeSea.render(frameData.rightProjectionMatrix, frameData.rightViewMatrix, stats, t);

            vrDisplay.submitFrame();
          } else {
            gl.viewport(0, 0, webglCanvas.width, webglCanvas.height);
            mat4.perspective(projectionMat, Math.PI*0.4, webglCanvas.width / webglCanvas.height, 0.1, 1024.0);
            cubeSea.render(projectionMat, frameData.leftViewMatrix, stats, t);
            stats.renderOrtho();
          }
        } else {
          window.requestAnimationFrame(onAnimationFrame);

          // No VRDisplay found.
          gl.viewport(0, 0, webglCanvas.width, webglCanvas.height);
          mat4.perspective(projectionMat, Math.PI*0.4, webglCanvas.width / webglCanvas.height, 0.1, 1024.0);
          mat4.identity(viewMat);
          cubeSea.render(projectionMat, viewMat, stats, t);

          stats.renderOrtho();
        }

        stats.end();
      }
      })();
    </script>
  </body>
</html>
